package com.example.blogsystem.controller;
import com.example.blogsystem.enums.ResultCodeEnum;
import com.example.blogsystem.model.Result;
import com.example.blogsystem.model.UserInfo;
import com.example.blogsystem.service.UserService;
import com.example.blogsystem.utils.JwtUtils;
import com.example.blogsystem.utils.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
@RequestMapping("/user")
@RestController
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String userName,String password){
        UserInfo user = userService.getUser(userName);
        System.out.println("执行方法");
        if(!StringUtils.hasLength(userName)) {
            return Result.fail(ResultCodeEnum.NO_EXIST_USERNAME.getCode(),"用户不存在在");
        }

        Assert.hasLength(password,"密码不能为空");
        try {
            if(!SecurityUtils.verify(password,user.getPassword())) {
                return Result.fail(ResultCodeEnum.PASSWORD_FAIL.getCode(), "密码错误");
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } System.out.println("执行1");
        //账号密码正确后验证JWT令牌
        Map<String,Object> cliams = new HashMap<>();
        System.out.println("执行2");
        cliams.put("id",user.getId());
        cliams.put("name",user.getUserName());
        System.out.println("执行2");
        String jwt = JwtUtils.genJWT(cliams);
        System.out.println("执行2");
        log.info(jwt);
        System.out.println(jwt);
        return Result.success(jwt);
    }
    @RequestMapping("/getAuthor")
    public Result getAuthorById(Integer id) {
        UserInfo user = userService.getAuthorById(id);
        return Result.success(user);
    }
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("user_token");
        //从token中获取用户id
        Integer userId = JwtUtils.getUserInfoToken(token);
        Assert.notNull(userId,"用户未登录");
        UserInfo userInfo = userService.selectUserInfobyId(userId);
        return userInfo;
    }
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId) {
        //根据博客id获取作者id
        //根据作者id获取作者信息
        Assert.notNull(blogId,"博客id不能为null");
        return userService.getAuthorById(blogId);
    }
}
